package com.liuguang.gateway.config.aspect;

import com.liuguang.common.exceptions.GlobalException;
import com.liuguang.common.pojo.CommonResult;
import org.aopalliance.intercept.Joinpoint;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @ClassName: LogAspect
 * @Description：
 * @Author: wanghr
 * Date: 1:23 PM 2020/9/13
 * Version: 1.0
 */
@Configuration
@Aspect
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut(value = "execution(public * com.liuguang.gateway..*Controller.*(..))")
    public void pointCut() {
    }

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long l = System.currentTimeMillis();
        String methodName = getMethodName(proceedingJoinPoint);
        printArgs(proceedingJoinPoint, methodName);
        Object result = proceedingJoinPoint.proceed();
        printResult(l, methodName, result);
        return result;
    }

    private void printResult(long l, String methodName, Object result) {
        logger.info("{}:执行时间:{}", methodName, System.currentTimeMillis() - l);
        if (result instanceof CommonResult) {
            CommonResult commonResult = (CommonResult) result;
            String msg = commonResult.getMsg();
            logger.info("执行结果：{}", msg);
        }
    }

    private String getMethodName(ProceedingJoinPoint proceedingJoinPoint) {
        Signature signature = proceedingJoinPoint.getSignature();
        String methodName = signature.getName();
        int i = methodName.lastIndexOf(".");
        methodName = methodName.substring(i + 1);
        return methodName;
    }

    private void printArgs(ProceedingJoinPoint proceedingJoinPoint, String methodName) {
        Object[] args = proceedingJoinPoint.getArgs();
        if (ObjectUtils.isNotEmpty(args)) {
//            ArrayList<Object> list = new ArrayList<>(Arrays.asList(args));
//            ArrayList<Object> params = new ArrayList<>();
//            list.forEach(p->{
//
//            });
            logger.info("进入方法：{}，入参：{}", methodName, args);
            return;
        }
        logger.info("进入方法：{}，无入参", methodName);
    }
}
